package cn.jsu.oj.dispatchServer.satellite.netty.starter;

import cn.jsu.oj.dispatchServer.satellite.annotation.StarterAnn;
import cn.jsu.oj.dispatchServer.satellite.config.ResourceConfig;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.ActiveNet;
import cn.jsu.oj.dispatchServer.satellite.server.SatelliteServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 验证启动器
 *
 * @author shan
 * @date 2022/07/07
 */
@Slf4j
@Component("verifyStarter")
@StarterAnn(starter = 2)
public class VerifyStarter implements Starter {

    @Autowired
    SatelliteServer satelliteServer;

    @Autowired
    ScheduledThreadPoolExecutor scheduleService;
    
    private static final String PASSWORD = ResourceConfig.getConfigString("client-active-password");

    private static final Integer REAL_PORT = ResourceConfig.getConfigInteger("client-active-real-port");

    private static final Integer VERIFY_SLEEP = ResourceConfig.getConfigInteger("client-active-verify-sleep");
    
    private Boolean isRun = false;
    
    private ScheduledFuture<?> scheduledFuture;

    @Override
    public void start() {
        if (this.isRun) {
            return;
        }
        this.isRun = true;
        log.info("----------验证调度开始......");
        this.scheduledFuture = scheduleService.scheduleAtFixedRate(() -> {
            if (SatelliteStarter.activeSign && !SatelliteStarter.verifySign) {
                log.info("----------验证尝试中......");
                try {
                    satelliteServer.getChannel()
                            .writeAndFlush(new ActiveNet(PASSWORD, REAL_PORT)
                                    .serialize());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (SatelliteStarter.verifySign && SatelliteStarter.activeSign) {
                scheduleService.setRemoveOnCancelPolicy(true);
                Objects.requireNonNull(this.scheduledFuture
                        , "----------调度未来为空，任务中断失败......")
                        .cancel(true);
                log.info("----------验证调度结束，验证任务已移除......");
                this.isRun = false;
            }
        }, VERIFY_SLEEP, VERIFY_SLEEP, TimeUnit.MILLISECONDS);
    }
}
